package com.sh.apiorder.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.sh.apicommon.entity.Order;
import com.sh.apicommon.service.ApiBackendService;
import com.sh.apiorder.service.TOrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

/**
 * 订单超时处理
 */
@Component
@Slf4j
public class OrderDelayQueueListener {

    @DubboReference
    private ApiBackendService apiBackendService;

    @Resource
    private TOrderService orderService;

    @Resource
    private JmsTemplate jmsTemplate;

    @JmsListener(destination = "orderHandler-delay-queue")
    public void processDeadLetterQueue(String message) {
        log.info("监听到延时队列的消息:{}", message);
        // 订单支付是否成功  没成功就回滚并且改状态  成功就不管
        Gson gson = new Gson();
        Order order = gson.fromJson(message, Order.class);
        Order orderById = orderService.getById(order.getId());
        if ( orderById.getStatus().equals(0)){   // 如果还没有支付
            Long interfaceId = orderById.getInterfaceId();
            Integer count = orderById.getCount();
            try {
                boolean result = apiBackendService.recoverInterfaceStock(interfaceId, count);
                if (!result){
                    log.error("回滚库存失败");
                    throw new RuntimeException("回滚库存失败");
                }
                UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", order.getId()).set("status", 2);
                boolean update = orderService.update(updateWrapper);
            } catch (Exception e) {
                log.error("回滚库存失败,重新入队");
                retryMessage(message);
                //
//                throw new RuntimeException(e);
            }
        }
    }

    private void retryMessage(String message) {
        jmsTemplate.convertAndSend("orderHandler-delay-queue", message);
    }


}
